﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Net;
using System.Runtime.InteropServices;


namespace NetworkScanner
{
    class ARPTools
    {
        [DllImport("iphlpapi.dll", ExactSpelling = true)]
        public static extern int SendARP(
        int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);

        /// <summary>
        /// Resuelve una direccion MAC a partir de una Direccion IP (ARP)
        /// </summary>
        /// <param name="IPAddr">La direccion IP</param>
        /// <returns>La direccion MAC resuelta</returns>
        public static PhysicalAddress ARP(IPAddress IPAddr)
        {
            int result = -1;
            byte[] macAddr = new byte[6];
            uint macAddrLen = (uint)macAddr.Length;
            string MACstr = "";
            PhysicalAddress mac = PhysicalAddress.None;

            try
            {
                result = SendARP(IPAddr.IPtoInt(), 0, macAddr, ref macAddrLen);
            }
            catch (Exception) { }

            if (result == 0)
            {
                for (int i = 0; i < macAddrLen; i++)
                {
                    MACstr += macAddr[i].ToString("X2");
                }
                try
                {
                    mac = PhysicalAddress.Parse(MACstr);
                }
                catch (Exception) { }
            }
            return mac;
        }


    }
}
